from django.shortcuts import render,HttpResponse
from django.contrib.auth import authenticate, login
from .forms import LoginForm,RegistrationForm,UserProfileForm

# Create your views here.


def user_login(request):
    if request.method == "GET":
        login_form=LoginForm()
        return render(request,"account/login.html",{"form":login_form})
    elif request.method == "POST":
        login_form = LoginForm(request.POST)
        if login_form.is_valid():
            cd = login_form.cleaned_data
            user = authenticate(username=cd["username"],password=cd["password"])
            if user:
                login(request,user)
                return HttpResponse("Wellcome You. You have been authenticated successfully")
            else:
                return HttpResponse("Sorry. Your username or password is not right.")
        else:
            return HttpResponse("Sorry. Invalid login.")


def register(request):
    if request.method == "POST":
        register_form = RegistrationForm(request.POST)
        user_profile_form = UserProfileForm(request.POST)
        if register_form.is_valid()*user_profile_form.is_valid():
            user = register_form.save(commit=False)
            user.set_password(register_form.cleaned_data["password"])
            user.save()
            user_profile = user_profile_form.save(commit=False)
            user_profile.user = user
            user_profile.save()
            return HttpResponse("Regist successfully.")
        else:
            return HttpResponse("Sorry you can't regist!")
    elif request.method == "GET":
        register_form= RegistrationForm()
        user_profile_form = UserProfileForm()
        return render(request,"account/register.html",{"form":register_form,"profile":user_profile_form})

